package DataStructure.queue;

//顺序队列
public class SeqQueue<E> implements MyQueue<E>{
    private E[] e;//元素数组(循环)
    private int head;//头指针
    private int tail;//尾指针

    public SeqQueue() {
        e= (E[]) new Object[4];
        head=0;
        tail=-1;
    }
    //扩充容量
    private void grow(){
        E[] tmp=e;
        e=(E[]) new Object[size()*2];
        for (int i = head; i<=tail ; i++) {
            e[i-head]=tmp[i%size()];
        }
        tail=size()-1;
        head=0;
    }
    //缩减容量
    private void cut(){

    }

    @Override
    public E first() {
        if(isEmpty())
            return null;
        return e[head%e.length];
    }

    @Override
    public E last() {
        if(isEmpty())
            return null;
        return e[tail%e.length];
    }

    @Override
    public void push(E e) {
        if(size()==this.e.length)
            grow();
        this.e[(++tail)%this.e.length]=e;
    }

    @Override
    public E poll() {
        if(isEmpty())
            return null;
        return e[(head++)%e.length];
    }

    @Override
    public int size() {
        return tail-head+1;
    }

    @Override
    public boolean isEmpty() {
        return head>tail;
    }

    @Override
    public void clear() {
        e= (E[]) new Object[4];
        head=0;
        tail=-1;
    }

    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder("[");
        for (int i = head; i <= tail; i++) {
            sb.append(e[i%e.length]);
            if(i!=tail)
                sb.append(",");
        }
        sb.append("]");
        return "SeqQueue{" +
                "e=" + sb +
                ", head=" + head +
                ", tail=" + tail +
                '}';
    }
}
